package cate.game.role.res.channelgift;

import cate.common.table.res.channelgift.ChannelGiftBaseRow;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import cate.game.role.res.channelgift.core.SingleChannelGiftPO;
import cate.game.role.res.channelgift.msg.ChannelGiftInfoResp;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;

import java.util.HashMap;
import java.util.Map;

@NoteClass("渠道礼包")
public class RoleChannelGift extends RoleDependent {
    @NoteField("所有的渠道礼包")
    public Map<Integer, SingleChannelGiftPO> allGifts;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (allGifts == null) {
            allGifts = new HashMap<>();
        }
        allGifts.values().forEach(po -> po.initialize(role));
    }

    @Override
    public void onEnter() {
        super.onEnter();
        excelCheck();
    }

    /**
     * 数据兼容
     */
    private void excelCheck() {
        allGifts.entrySet().removeIf(entry -> role.getGame().table.channelGift.base.get(entry.getKey()) == null);
        for (ChannelGiftBaseRow config : role.getGame().table.channelGift.base.getList()) {
            if (!allGifts.containsKey(config.id)) {
                allGifts.put(config.id, new SingleChannelGiftPO(config.id, role));
            }
        }
    }

    /**
     * 同步消息到前端
     */
    public void noticeUpdate() {
        role.sendNow(new ChannelGiftInfoResp(allGifts));
    }

    /**
     * 领取礼包奖励
     *
     * @param tid 礼包配置ID
     * @return 领取结果
     */
    public EcResult<Void> receiveGift(int tid) {
        EcResult<Void> r = new EcResult<>();
        if (!allGifts.containsKey(tid)) {
            return r.fail("礼包不存在");
        }
        r = allGifts.get(tid).receiveGift();
        if (r.ok()) {
            noticeUpdate();
        }
        return r;
    }

    @Override
    public void onDaySpan(boolean silence) {
        if (allGifts != null) {
            allGifts.values().forEach(po -> po.onDaySpanSafe(silence));
        }
        noticeUpdate();
    }

    @Override
    public void onWeekSpan(boolean silence) {
        if (allGifts != null) {
            allGifts.values().forEach(po -> po.onWeekSpanSafe(silence));
        }
        noticeUpdate();
    }

    @Override
    public void onMonthSpan(boolean silence) {
        if (allGifts != null) {
            allGifts.values().forEach(po -> po.onMonthSpanSafe(silence));
        }
        noticeUpdate();
    }
}
